package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ListWheelAdapter;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.ViewSuppDetail;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.view.StartTimeItemLayout;

/**
 * 纠错
 * 
 * @author xi
 * 
 */
public class UpdateActivity extends Activity implements OnClickListener {

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;
	private ImageView map_icon;
	private final int GET_ADDRESS_RESULT_CODE = 0x1120;
	private final int DO_SUBMIT_SUCCESS = GET_ADDRESS_RESULT_CODE + 1;
	private final int DO_SUBMIT_FAIL = GET_ADDRESS_RESULT_CODE + 2;

	private EditText address_et;
	private EditText shopname_et;
	private EditText tel_et;
	private EditText descr_et;

	private String[] weeks = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
	private Button startTime_Ok;
	private Button endTime_Ok;
	private TextView startTime;
	private TextView endTime;

	private Dialog startTimeDialog;
	private Dialog endTimeDialog;
	private LayoutInflater inflater;
	private RelativeLayout start_ll;
	private LinearLayout startTime_ll;
	private RelativeLayout endTime_rl;
	private Context context;
	private Button submit_button;
	private Dialog dialog;
	private Activity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		context = this;
		activity = this;
		setContentView(R.layout.activity_update);
		initRes();
		initData();
	}

	private void initRes() {
		dialog = DialogUtil.createProgressDialog(activity, "纠错", "信息提交中!");
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("店铺纠错");
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);

		map_icon = (ImageView) findViewById(R.id.map_icon);
		map_icon.setOnClickListener(this);
		address_et = (EditText) findViewById(R.id.address_et);

		startTime = (TextView) findViewById(R.id.startTime);
		startTime.setOnClickListener(this);
		endTime = (TextView) findViewById(R.id.endTime);
		endTime.setOnClickListener(this);

		inflater = getLayoutInflater();
		start_ll = (RelativeLayout) inflater.inflate(R.layout.starttime_dialog,
				null);
		startTime_ll = (LinearLayout) start_ll.findViewById(R.id.start_ll);

		for (int i = 0; i < weeks.length; i++) {
			StartTimeItemLayout layout = new StartTimeItemLayout(this);
			layout.setValue(weeks[i]);
			startTime_ll.addView(layout);
		}
		startTime_Ok = (Button) start_ll.findViewById(R.id.startTime_Ok);
		startTime_Ok.setOnClickListener(this);

		endTime_rl = (RelativeLayout) inflater.inflate(R.layout.endtime_dialog,
				null);
		endTime_Ok = (Button) endTime_rl.findViewById(R.id.endTime_Ok);
		endTime_Ok.setOnClickListener(this);
		shopname_et = (EditText) findViewById(R.id.shopname_et);
		tel_et = (EditText) findViewById(R.id.tel_et);
		descr_et = (EditText) findViewById(R.id.descr_et);
		submit_button = (Button) findViewById(R.id.submit_button);
		submit_button.setOnClickListener(this);
		initTimeRes();
	}

	ViewSuppDetail detail;

	private void initData() {
		detail = (ViewSuppDetail) getIntent().getSerializableExtra("detail");
		if (detail == null) {
			LogUtil.d("wxf", "detail is null");
		} else {
			LogUtil.d("wxf", "info:" + detail.getSupInfo());
			shopname_et.setText(detail.getSuppName());
			address_et.setText(detail.getAddr());
			tel_et.setText(detail.getTelPhone());
			descr_et.setText(detail.getSupInfo());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private void doSubmitData() {

		final String shopName = shopname_et.getText().toString();
		final String addr = address_et.getText().toString();
		final String tel = tel_et.getText().toString();
		final String des = descr_et.getText().toString();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {

					// String url = "supp.id=" + detail.getId()
					// + "&supp.suppName=" + shopName + "&supp.telPhone="
					// + tel + "&supp.shopHours=" + detail.getShopHours()
					// + "&supp.supInfo=" + des + "&supp.addr=" + addr;

					Map<String, String> map = new HashMap<String, String>();
					map.put("supp.id", detail.getId());
					map.put("supp.suppName", shopName);
					map.put("supp.telPhone", tel);
					map.put("supp.shopHours", detail.getShopHours());
					map.put("supp.supInfo", des);
					map.put("supp.addr", addr);
					String result = HttpClientUtil.postFromWebByHttp(context,
							Urls.UPDATE_SHOP_INFO, map);

					LogUtil.d("wxf", "result:" + result);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = DO_SUBMIT_FAIL;
						handler.sendMessage(msg);
					} else {
						JSONObject obj = new JSONObject(result);
						String message = null;
						if (!obj.isNull("message")) {
							message = obj.getString("message");
						}

						int state = obj.getInt("state");
						if (state == 200) {
							Message msg = handler.obtainMessage();
							msg.what = DO_SUBMIT_SUCCESS;
							msg.obj = message;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = DO_SUBMIT_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}

					}

				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = DO_SUBMIT_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "doSubmitData:" + e.toString());
				}

			}
		}).start();
	}

	private boolean doCheck() {
		String shopName = shopname_et.getText().toString();
		String telName = tel_et.getText().toString();
		String address = address_et.getText().toString();
		String des = descr_et.getText().toString();
		if (shopName.length() == 0) {
			Toast.makeText(context, "店铺名字不能为空!", 500).show();
			return false;
		}
		if (telName.length() == 0) {
			Toast.makeText(context, "电话不能为空!", 500).show();
			return false;
		}
		if (address.length() == 0) {
			Toast.makeText(context, "地址不能为空!", 500).show();
			return false;
		}
		if (des.length() == 0) {
			Toast.makeText(context, "描述不能为空!", 500).show();
			return false;
		}
		if (shopName.equals(detail.getSuppName())
				&& telName.equals(detail.getTelPhone())
				&& address.equals(detail.getAddr())
				&& des.equals(detail.getSupInfo())) {
			Toast.makeText(context, "请修改以后再提交", 500).show();
			return false;
		}
		return true;
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			if (dialog != null)
				dialog.dismiss();
			switch (msg.what) {
			case DO_SUBMIT_SUCCESS:
				String s = "提交成功";
				if (msg.obj != null) {
					s = msg.obj.toString();
				}
				Toast.makeText(context, s, 500).show();
				finish();
				break;
			case DO_SUBMIT_FAIL:
				String str = "提交失败";
				if (msg.obj != null) {
					str = msg.obj.toString();
				}
				Toast.makeText(context, str, 500).show();
				break;
			}
		};
	};

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.map_icon:
			intent = new Intent(this, AddressActivity.class);
			intent.putExtra("address", detail.getAddr());
			startActivityForResult(intent, GET_ADDRESS_RESULT_CODE);
			break;
		case R.id.startTime:

			if (startTimeDialog == null) {
				startTimeDialog = new Dialog(this, R.style.QuitDialog);
				startTimeDialog.setContentView(start_ll);
			}
			Window dialogWindow = startTimeDialog.getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.CENTER);
			lp.width = 400; // 宽度
			lp.height = 500; // 高度
			dialogWindow.setAttributes(lp);
			startTimeDialog.show();
			break;
		case R.id.endTime:
			if (endTimeDialog == null) {
				endTimeDialog = new Dialog(this, R.style.QuitDialog);
				endTimeDialog.setContentView(endTime_rl);
			}
			Window endWidow = endTimeDialog.getWindow();
			WindowManager.LayoutParams endLp = endWidow.getAttributes();
			endWidow.setGravity(Gravity.CENTER);
			endLp.width = 400; // 宽度
			endLp.height = 400; // 高度
			endWidow.setAttributes(endLp);
			endTimeDialog.show();
			break;
		case R.id.startTime_Ok:
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < startTime_ll.getChildCount(); i++) {
				StartTimeItemLayout layout = (StartTimeItemLayout) startTime_ll
						.getChildAt(i);
				if (layout.isCheckValue()) {
					LogUtil.d("wxf", layout.getValue());
					sb.append(layout.getValue() + ",");
				}
			}
			startTime.setText(sb.toString());
			startTimeDialog.dismiss();
			break;
		case R.id.endTime_Ok:
			endTimeDialog.dismiss();
		case R.id.submit_button:
			if (doCheck()) {
				if (dialog != null)
					dialog.show();
				doSubmitData();
			}

			break;
		}
	}

	private List<String> hours;
	private List<String> mins;

	private void initTimeRes() {
		final WheelView hour = (WheelView) endTime_rl.findViewById(R.id.hour);
		final WheelView minute = (WheelView) endTime_rl
				.findViewById(R.id.minute);
		final WheelView end_hour = (WheelView) endTime_rl
				.findViewById(R.id.hour_end);
		final WheelView end_minute = (WheelView) endTime_rl
				.findViewById(R.id.minute_end);
		OnWheelChangedListener listener = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {

			}
		};

		hour.setInterpolator(new AnticipateOvershootInterpolator());
		minute.setInterpolator(new AnticipateOvershootInterpolator());
		end_hour.setInterpolator(new AnticipateOvershootInterpolator());
		end_minute.setInterpolator(new AnticipateOvershootInterpolator());
		hours = new ArrayList<String>();
		for (int i = 0; i < 24; i++) {
			if (i < 10) {
				hours.add("0" + i);
			} else {
				hours.add(i + "");
			}
		}
		Calendar calendar = Calendar.getInstance();
		int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
		hour.setViewAdapter(new DateListAdapter(this, hours, 0));
		hour.setCurrentItem(currentHour);
		hour.addChangingListener(listener);

		end_hour.setViewAdapter(new DateListAdapter(this, hours, 0));
		end_hour.setCurrentItem(currentHour);
		end_hour.addChangingListener(listener);

		mins = new ArrayList<String>();
		for (int i = 0; i < 60; i++) {
			if (i < 10) {
				mins.add("0" + i);
			} else {
				mins.add(i + "");
			}
		}
		int min = calendar.get(Calendar.MINUTE);
		minute.setViewAdapter(new DateListAdapter(this, mins, 0));
		minute.setCurrentItem(min);
		minute.addChangingListener(listener);

		end_minute.setViewAdapter(new DateListAdapter(this, mins, 0));
		end_minute.setCurrentItem(min);
		end_minute.addChangingListener(listener);
	}

	private class DateListAdapter extends ListWheelAdapter<String> {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateListAdapter(Context context, List<String> items, int current) {
			super(context, items);
			this.currentValue = current;
			setTextSize(16);
		}

		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
				// view.setTextColor(0xFF0000F0);
			}
			view.setTypeface(Typeface.DEFAULT);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case GET_ADDRESS_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				String addressData = data.getStringExtra("address");
				LogUtil.d("wxf", "addressData:" + addressData);
				if (addressData != null) {
					address_et.setText(addressData);
				}
			}
		}
	}
}
